package cn.py.boot_lua.processTa.impl;

import cn.py.boot_lua.handler.admin.RequestTask;
import cn.py.boot_lua.handler.generic.GenericQueueService;
import cn.py.boot_lua.handler.generic.QueueType;
import cn.py.boot_lua.handler.impl.ImageBackServiceImpl;
import cn.py.boot_lua.processTa.Strategy;
import cn.py.boot_lua.processTa.TaskProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Semaphore;

@Slf4j
@Strategy(QueueType.BACK_IMG)
@Component
public class BackTaskStrategy implements TaskProcessStrategy{

    private final ImageBackServiceImpl imageBackService;
    public BackTaskStrategy(ImageBackServiceImpl imageBackService) {
        this.imageBackService = imageBackService;
    }

    @Override
    public void process(RequestTask task, Semaphore semaphore, GenericQueueService genericQueueService) {
        try {
            semaphore.acquire();
            log.info("图像背景获取信号量许可: {}", task.getRequestId());
            imageBackService.backImgHandleAsync(task, () -> {
                log.info("图像背景生成任务ID: {} 处理完成", task.getRequestId());
                semaphore.release();
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("图像背景任务被中断", e);
            semaphore.release();
        } catch (Exception e) {
            log.error("图像背景任务处理失败", e);
            semaphore.release();
        }
    }
}
